import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getUserProfile, updateUserProfile } from '../../services/auth';
import useAuthStore from '../../store/auth';
import usePaymentStore from '../../store/payment';

const Profile: React.FC = () => {
  const [profileData, setProfileData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [updateLoading, setUpdateLoading] = useState(false);
  const [error, setError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  
  // 编辑表单状态
  const [editMode, setEditMode] = useState(false);
  const [nickname, setNickname] = useState('');
  const [gender, setGender] = useState<number>(1);
  const [birthYear, setBirthYear] = useState<string>('');
  const [birthMonth, setBirthMonth] = useState<string>('');
  const [birthDay, setBirthDay] = useState<string>('');
  const [birthHour, setBirthHour] = useState<string>('');
  
  const navigate = useNavigate();
  const { user, updateUser } = useAuthStore();
  const walletBalance = usePaymentStore(state => state.wallet.balance);
  
  useEffect(() => {
    fetchUserProfile();
  }, []);
  
  const fetchUserProfile = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await getUserProfile();
      
      if (response.code === 200) {
        setProfileData(response.data);
        
        // 初始化编辑表单数据
        setNickname(response.data.nickname || '');
        setGender(response.data.gender || 1);
        setBirthYear(response.data.birthYear?.toString() || '');
        setBirthMonth(response.data.birthMonth?.toString() || '');
        setBirthDay(response.data.birthDay?.toString() || '');
        setBirthHour(response.data.birthHour?.toString() || '');
      } else {
        setError(response.message || '获取用户信息失败');
      }
    } catch (err: any) {
      setError(err.message || '获取用户信息失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      setUpdateLoading(true);
      setError('');
      setSuccessMessage('');
      
      const updateData = {
        nickname,
        gender,
        birthYear: birthYear ? parseInt(birthYear) : undefined,
        birthMonth: birthMonth ? parseInt(birthMonth) : undefined,
        birthDay: birthDay ? parseInt(birthDay) : undefined,
        birthHour: birthHour ? parseInt(birthHour) : undefined
      };
      
      const response = await updateUserProfile(updateData);
      
      if (response.code === 200) {
        // 更新成功
        setSuccessMessage('个人信息更新成功');
        setEditMode(false);
        
        // 更新本地用户信息
        updateUser({
          ...user!,
          nickname
        });
        
        // 重新获取用户信息
        fetchUserProfile();
      } else {
        setError(response.message || '更新用户信息失败');
      }
    } catch (err: any) {
      setError(err.message || '更新用户信息失败，请稍后再试');
    } finally {
      setUpdateLoading(false);
    }
  };
  
  // 生成年份选项
  const generateYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let year = currentYear - 100; year <= currentYear; year++) {
      years.push(year);
    }
    return years.reverse();
  };
  
  // 生成月份选项
  const generateMonthOptions = () => {
    const months = [];
    for (let month = 1; month <= 12; month++) {
      months.push(month);
    }
    return months;
  };
  
  // 生成日期选项
  const generateDayOptions = () => {
    const days = [];
    for (let day = 1; day <= 31; day++) {
      days.push(day);
    }
    return days;
  };
  
  // 生成时辰选项
  const generateHourOptions = () => {
    return [
      { value: 1, label: '子时 (23:00-01:00)' },
      { value: 2, label: '丑时 (01:00-03:00)' },
      { value: 3, label: '寅时 (03:00-05:00)' },
      { value: 4, label: '卯时 (05:00-07:00)' },
      { value: 5, label: '辰时 (07:00-09:00)' },
      { value: 6, label: '巳时 (09:00-11:00)' },
      { value: 7, label: '午时 (11:00-13:00)' },
      { value: 8, label: '未时 (13:00-15:00)' },
      { value: 9, label: '申时 (15:00-17:00)' },
      { value: 10, label: '酉时 (17:00-19:00)' },
      { value: 11, label: '戌时 (19:00-21:00)' },
      { value: 12, label: '亥时 (21:00-23:00)' }
    ];
  };
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto">
        <div className="bg-white shadow overflow-hidden sm:rounded-lg">
          <div className="px-4 py-5 sm:px-6 flex justify-between items-center">
            <div>
              <h3 className="text-lg leading-6 font-medium text-gray-900">个人中心</h3>
              <p className="mt-1 max-w-2xl text-sm text-gray-500">个人信息与账户管理</p>
            </div>
            {!editMode && (
              <button
                onClick={() => setEditMode(true)}
                className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                编辑资料
              </button>
            )}
          </div>
          
          {error && (
            <div className="px-4 py-3 bg-red-50 text-red-500 text-sm">
              {error}
            </div>
          )}
          
          {successMessage && (
            <div className="px-4 py-3 bg-green-50 text-green-500 text-sm">
              {successMessage}
            </div>
          )}
          
          {editMode ? (
            <div className="border-t border-gray-200">
              <form onSubmit={handleUpdateProfile} className="p-4 sm:p-6">
                <div className="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                  <div className="sm:col-span-3">
                    <label htmlFor="nickname" className="block text-sm font-medium text-gray-700">
                      昵称
                    </label>
                    <div className="mt-1">
                      <input
                        type="text"
                        id="nickname"
                        className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
                        value={nickname}
                        onChange={(e) => setNickname(e.target.value)}
                      />
                    </div>
                  </div>
                  
                  <div className="sm:col-span-3">
                    <label className="block text-sm font-medium text-gray-700">
                      性别
                    </label>
                    <div className="mt-1 flex items-center space-x-4">
                      <div className="flex items-center">
                        <input
                          id="male"
                          name="gender"
                          type="radio"
                          checked={gender === 1}
                          onChange={() => setGender(1)}
                          className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                        />
                        <label htmlFor="male" className="ml-2 block text-sm text-gray-700">
                          男
                        </label>
                      </div>
                      <div className="flex items-center">
                        <input
                          id="female"
                          name="gender"
                          type="radio"
                          checked={gender === 2}
                          onChange={() => setGender(2)}
                          className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                        />
                        <label htmlFor="female" className="ml-2 block text-sm text-gray-700">
                          女
                        </label>
                      </div>
                    </div>
                  </div>
                  
                  <div className="sm:col-span-6">
                    <label className="block text-sm font-medium text-gray-700">
                      出生日期和时辰
                    </label>
                    <div className="mt-1 grid grid-cols-4 gap-4">
                      <div>
                        <select
                          id="birth-year"
                          className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
                          value={birthYear}
                          onChange={(e) => setBirthYear(e.target.value)}
                        >
                          <option value="">选择年份</option>
                          {generateYearOptions().map(year => (
                            <option key={year} value={year}>{year}年</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <select
                          id="birth-month"
                          className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
                          value={birthMonth}
                          onChange={(e) => setBirthMonth(e.target.value)}
                        >
                          <option value="">选择月份</option>
                          {generateMonthOptions().map(month => (
                            <option key={month} value={month}>{month}月</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <select
                          id="birth-day"
                          className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
                          value={birthDay}
                          onChange={(e) => setBirthDay(e.target.value)}
                        >
                          <option value="">选择日期</option>
                          {generateDayOptions().map(day => (
                            <option key={day} value={day}>{day}日</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <select
                          id="birth-hour"
                          className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
                          value={birthHour}
                          onChange={(e) => setBirthHour(e.target.value)}
                        >
                          <option value="">选择时辰</option>
                          {generateHourOptions().map(hour => (
                            <option key={hour.value} value={hour.value}>{hour.label}</option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <p className="mt-2 text-sm text-gray-500">
                      准确的出生信息有助于更精确的八字和命理分析
                    </p>
                  </div>
                </div>
                
                <div className="mt-6 flex justify-end space-x-3">
                  <button
                    type="button"
                    onClick={() => setEditMode(false)}
                    className="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    disabled={updateLoading}
                    className={`inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${updateLoading ? 'opacity-70 cursor-not-allowed' : ''}`}
                  >
                    {updateLoading ? '保存中...' : '保存'}
                  </button>
                </div>
              </form>
            </div>
          ) : (
            <div className="border-t border-gray-200">
              <dl>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">用户名</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{profileData?.username}</dd>
                </div>
                <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">昵称</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{profileData?.nickname || '未设置'}</dd>
                </div>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">性别</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{profileData?.gender === 1 ? '男' : profileData?.gender === 2 ? '女' : '未设置'}</dd>
                </div>
                <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">出生日期</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                    {profileData?.birthYear && profileData?.birthMonth && profileData?.birthDay
                      ? `${profileData.birthYear}年${profileData.birthMonth}月${profileData.birthDay}日`
                      : '未设置'}
                  </dd>
                </div>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">出生时辰</dt>
                  <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                    {profileData?.birthHour
                      ? generateHourOptions().find(h => h.value === profileData.birthHour)?.label
                      : '未设置'}
                  </dd>
                </div>
                <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">会员状态</dt>
                  <dd className="mt-1 text-sm sm:mt-0 sm:col-span-2">
                    {profileData?.isVip ? (
                      <div>
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                          VIP会员
                        </span>
                        <span className="ml-2 text-gray-500">
                          到期时间: {profileData.vipExpireTime}
                        </span>
                      </div>
                    ) : (
                      <div className="flex items-center">
                        <span className="text-gray-500">普通用户</span>
                        <button
                          onClick={() => navigate('/vip')}
                          className="ml-3 inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        >
                          开通VIP
                        </button>
                      </div>
                    )}
                  </dd>
                </div>
                <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                  <dt className="text-sm font-medium text-gray-500">钱包余额</dt>
                  <dd className="mt-1 text-sm sm:mt-0 sm:col-span-2">
                    <div className="flex items-center">
                      <span className="text-gray-900 font-medium">¥ {walletBalance.toFixed(2)}</span>
                      <button
                        onClick={() => navigate('/wallet')}
                        className="ml-3 inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      >
                        充值
                      </button>
                    </div>
                  </dd>
                </div>
              </dl>
            </div>
          )}
        </div>
        
        <div className="mt-6 flex justify-center space-x-4">
          <button
            onClick={() => navigate('/orders')}
            className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            我的订单
          </button>
          <button
            onClick={() => navigate('/bazi')}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            八字分析
          </button>
        </div>
      </div>
    </div>
  );
};

export default Profile;
